package cn.com.tianpeidong.restaurantadmin.project.admin.pos.entity;

import cn.com.tianpeidong.restaurantadmin.common.util.security.ShiroUtils;
import lombok.Data;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

import static cn.com.tianpeidong.restaurantadmin.project.admin.pos.constant.PosConstant.OPERATING;

/**
 * @author tianpeidong
 * @version 创建时间: 19-6-1 下午1:42
 */
@Data
public class Sale implements Serializable {

    private Long id;
    private Long deskId;
    private String deskCode;
    private String uuid;
    private Integer peopleNum;
    private List<SaleLineItem> saleLineItems;
    private BigDecimal total;
    private String date;
    private Long operatorId;
    private Integer status;
    private Date createdTime;

    public Sale() {
        this.uuid = "S_" + System.currentTimeMillis();
        this.saleLineItems = new ArrayList<>();
        this.total = new BigDecimal(0);
        this.operatorId = ShiroUtils.getUserId();
        this.status = OPERATING;
    }

    public BigDecimal getTotals() {
        BigDecimal total = new BigDecimal(0);
        for (SaleLineItem saleLineItem : saleLineItems) {
            total = total.add(saleLineItem.getSubTotal()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        }
        this.total = total;
        return total;
    }

    public void addSaleLineItem(SaleLineItem saleLineItem) {
        if (this.saleLineItems.contains(saleLineItem)) {
            int index = this.saleLineItems.indexOf(saleLineItem);
            SaleLineItem saleLineItem1 = this.saleLineItems.get(index);
            Collections.replaceAll(this.saleLineItems, saleLineItem1, saleLineItem);
            getTotals();
            return;
        }
        this.saleLineItems.add(saleLineItem);
        getTotals();
    }

    public void removeSaleLineItem(SaleLineItem saleLineItem) {
        this.saleLineItems.remove(saleLineItem);
        getTotals();
    }


}
